export interface ProgressCallback {
  loaded: number;
  total: number;
}

export function httpRequest(options: {
  method: string;
  url: string;
  data?: any;
  xhrInstance?: any;
  onProgress?: (params: ProgressCallback) => void;
}): Promise<any> {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    if (options.xhrInstance && typeof options.xhrInstance === 'object') {
      options.xhrInstance.instance = xhr;
    }

    xhr.open(options.method, options.url, true);

    xhr.upload.onprogress = (event: ProgressEvent) => {
      if (options.onProgress) {
        options.onProgress({ loaded: event.loaded, total: event.total });
      }
    };

    xhr.onabort = () => {
      reject('request aborted');
    };

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(xhr.responseText);
      } else {
        reject(new Error(`Request failed with status ${xhr.status}`));
      }
    };

    xhr.onerror = (err) => {
      reject(new Error('Network error'));
    };

    if (options.data) {
      xhr.send(options.data);
    } else {
      xhr.send();
    }
  });
}
